package com.itheima.upload4;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class UploadImage implements Runnable {
    private Socket accept;

    public UploadImage(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        BufferedWriter bw = null;
        try {
            InputStream is = accept.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(new FileOutputStream("day16\\copy\\" + UUID.randomUUID() + ".jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                //bytes  0, len
                bos.write(bytes, 0, len);
            }

            //3.给客户端 响应一个上传成功
            //字节流
            OutputStream os = accept.getOutputStream();
            //不能写汉字
            // OutputStreamWriter writer = ;
            bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("上传成功!");
            // accept.shutdownOutput();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源的代码
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
